<template>
  <div id="userLoginPage">
    <img class="logo" src="@/assets/xianrendong-logo.png" alt="logo" />
    <h2 class="title">仙人洞文旅 - 用户登录</h2>
    <div class="desc">仙人洞文旅</div>
    <a-form :model="formState" name="basic" autocomplete="off" @finish="handleSubmit">
      <a-form-item name="userAccount" :rules="[{ required: true, message: '请输入账号' }]">
        <a-input v-model:value="formState.userAccount" placeholder="请输入账号" />
      </a-form-item>
      <a-form-item
        name="userPassword"
        :rules="[
          { required: true, message: '请输入密码' },
          { min: 6, message: '密码长度不能小于 6 位' },
        ]"
      >
        <a-input-password v-model:value="formState.userPassword" placeholder="请输入密码" />
      </a-form-item>
      <div class="tips">
        没有账号？
        <RouterLink to="/user/register">去注册</RouterLink>
      </div>
      <a-form-item>
        <a-button type="primary" html-type="submit" style="width: 100%">登录</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>
<script lang="ts" setup>
import { reactive } from 'vue'
import { userLogin } from '@/api/userController'
import { useLoginUserStore } from '@/stores/useLoginUserStore'
import { message } from 'ant-design-vue'
import router from '@/router' // 用于接受表单输入的值

// 用于接受表单输入的值
const formState = reactive<API.UserLoginRequest>({
  userAccount: '',
  userPassword: '',
})

const loginUserStore = useLoginUserStore()

/**
 * 提交表单
 * @param values
 */
const handleSubmit = async (values: API.UserLoginRequest) => {
  try {
    // 发送登录请求
    const res = await userLogin(values)

    // 检查登录是否成功
    if (res.data.code === 200) {
      // 直接使用登录返回的用户信息更新状态
      if (res.data.data) {
        loginUserStore.setLoginUser(res.data.data)
      } else {
        // 如果登录返回没有用户信息，再调用获取用户信息接口
        await loginUserStore.fetchLoginUser()
      }

      message.success('登录成功')

      // 处理重定向
      const urlParams = new URLSearchParams(window.location.search)
      const redirect = urlParams.get('redirect')

      if (redirect) {
        window.location.href = decodeURIComponent(redirect)
      } else {
        await router.push({
          path: '/',
          replace: true,
        })
      }
    } else {
      message.error('登录失败：' + (res.data.message || '未知错误'))
    }
  } catch (error: unknown) {
    // 错误处理
    if (error && typeof error === 'object' && 'response' in error) {
      const axiosError = error as { response: { status: number; data: { message?: string } } }
      message.error(`登录失败：${axiosError.response.data?.message || '服务器错误'}`)
    } else if (error && typeof error === 'object' && 'request' in error) {
      message.error('网络连接失败，请检查网络连接')
    } else {
      message.error('登录过程中发生错误，请重试')
    }
  }
}
</script>

<style scoped>
#userLoginPage {
  max-width: 360px;
  margin: 0 auto;
}
.logo {
  margin-bottom: 16px;
  width: 80px;
  display: block;
  margin-left: auto; /* 添加水平居中 */
  margin-right: auto; /* 添加水平居中 */
}

.title {
  text-align: center;
  margin-bottom: 16px;
}

.desc {
  text-align: center;
  color: #bbb;
  margin-bottom: 16px;
}

.tips {
  color: #bbb;
  text-align: right;
  font-size: 13px;
  margin-bottom: 16px;
}
</style>
